package com.incar.chuxing.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.ui.camera.CameraThreadPool;
import com.google.android.cameraview.AspectRatio;
import com.google.android.cameraview.CameraView;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.RxApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.CarDetailBean;
import com.incar.chuxing.bean.OcrResultBean;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.ImageLoader;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.ocrlicense.ScannerFinderView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RecogCarPlateActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    @BindView(R.id.ll_scan_light)
    LinearLayout llScanLight;
    @BindView(R.id.qr_code_header_back)
    ImageView qrCodeHeaderBack;
    @BindView(R.id.iv_scan_light)
    ImageView ivScanLight;
    @BindView(R.id.finder_view)
    ScannerFinderView mQrCodeFinderView;
    @BindView(R.id.camera)
    CameraView mCameraView;
    @BindView(R.id.tv_take_picture)
    TextView takePicture;
    @BindView(R.id.tv_tip)
    TextView tvTip;


    private Handler mBackgroundHandler;
    private Context mContext = this;
    private String number;
    private SensorManager sensorManager;
    private boolean isLightOn = false;
    private static final String TAG = "RecogCarPlateActivity";
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final String FRAGMENT_DIALOG = "dialog";
    private static final int[] FLASH_OPTIONS = {
            CameraView.FLASH_AUTO,
            CameraView.FLASH_OFF,
            /*     CameraView.FLASH_ON,*/
    };
    private static final int[] FLASH_ICONS = {
            R.drawable.ic_flash_auto,
            R.drawable.ic_flash_off,
            /*         R.drawable.ic_flash_on,*/
    };
    private static final int[] FLASH_TITLES = {
            R.string.flash_auto,
            R.string.flash_off,
            /*     R.string.flash_on,*/
    };


    @Override
    public int getLayoutId() {
        return R.layout.activity_recognize_plate;
    }


    @Override
    public void initData() {
        super.initData();
        //不是同一天时候删除缓存
        if (SPUtils.getInstance(mContext).isToday()) {
            SPUtils.getInstance(mContext).removeValue(SPKey.OCR_TIMES_CONTT);
            SPUtils.getInstance(mContext).saveMsg();
        }
        initLightSenser();
    }

    @Override
    public void initView() {
        //设置启动界面全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        if (mCameraView != null) {
            mCameraView.addCallback(mCallback);
        }

        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(mContext, "tapScanTag");
                if (mCameraView != null) {
                    showLoadingDialog();
                    mCameraView.takePicture();

                }
            }
        });

        mQrCodeFinderView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }

    private void initLightSenser() {
        //首先要获取SensorManager传感器管理器服务：
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //获取光照传感器：
        Sensor liaghtSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);//Sensor.TYPE_LIGHT 代表光照传感器
        if (null != liaghtSensor) {
            //注册和监视光照传感器：
            //监视传感器的改变
            //accuracy 传感器的精度 通过event.accuracy获取
            //values 传感器传回的数值  如event.values[0] 获取光线强度lux
            //timestamp 传感器事件发生的时间（以纳秒为单位）
            //对传感器精度的改变做出反应
            sensorManager.registerListener(listener, liaghtSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    private SensorEventListener listener = new SensorEventListener() {
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // values数组中第一个下标的值就是当前的光照强度
            float value = event.values[0];
            if (value < 80) {
                llScanLight.setVisibility(View.VISIBLE);
            } else if (value >= 80 && !isLightOn) {
                llScanLight.setVisibility(View.INVISIBLE);
            }
        }

    };

    @OnClick({R.id.qr_code_header_back, R.id.ll_scan_light})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.qr_code_header_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.ll_scan_light:
                if (!isLightOn) {
                    if (mCameraView != null) {
                        mCameraView.setFlash(CameraView.FLASH_TORCH);
                    }
                    isLightOn = true;
                    ivScanLight.setImageDrawable(getResources().getDrawable(R.drawable.flashlight_open));
                    tvTip.setVisibility(View.VISIBLE);
                } else {
                    if (mCameraView != null) {
                        mCameraView.setFlash(CameraView.FLASH_OFF);
                    }
                    isLightOn = false;
                    ivScanLight.setImageDrawable(getResources().getDrawable(R.drawable.flashlight));
                    tvTip.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {

            try {
                mCameraView.start();
                //mCameraView.setFacing(CameraView.FACING_BACK);
                final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
                AspectRatio chosenRation = null;
                for (AspectRatio ratio : ratios) {
                    if ((double) ratio.getX() / (double) ratio.getY() == 16.0 / 9) {
                        chosenRation = ratio;
                    }
                }

                if (chosenRation == null) {
                    for (AspectRatio ratio : ratios) {
                        if ((double) ratio.getX() / (double) ratio.getY() == 4.0 / 3) {
                            chosenRation = ratio;
                        }
                    }
                }
                if (chosenRation != null) {
                    mCameraView.setAspectRatio(chosenRation);
                } else {
                    return;
                }

            } catch (RuntimeException e) {
                ToastUtils.makeText(RecogCarPlateActivity.this, "相机启动异常，请尝试重启手机", ToastUtils.LENGTH_SHORT).show();
            }


        } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            ConfirmationDialogFragment
                    .newInstance(R.string.camera_permission_plate,
                            new String[]{Manifest.permission.CAMERA},
                            REQUEST_CAMERA_PERMISSION,
                            R.string.camera_permission_not_plate)
                    .show(getSupportFragmentManager(), FRAGMENT_DIALOG);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        }
    }

    @Override
    protected void onPause() {
        mCameraView.stop();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBackgroundHandler != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                mBackgroundHandler.getLooper().quitSafely();
            } else {
                mBackgroundHandler.getLooper().quit();
            }
            mBackgroundHandler = null;
        }

        if (null != listener) {
            sensorManager.unregisterListener(listener);
        }
    }

    private Handler getBackgroundHandler() {
        if (mBackgroundHandler == null) {
            HandlerThread thread = new HandlerThread("background");
            thread.start();
            mBackgroundHandler = new Handler(thread.getLooper());
        }
        return mBackgroundHandler;
    }

    public static class ConfirmationDialogFragment extends DialogFragment {
        private static final String ARG_MESSAGE = "message";
        private static final String ARG_PERMISSIONS = "permissions";
        private static final String ARG_REQUEST_CODE = "request_code";
        private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";

        public static ConfirmationDialogFragment newInstance(@StringRes int message,
                                                             String[] permissions, int requestCode, @StringRes int notGrantedMessage) {
            ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_MESSAGE, message);
            args.putStringArray(ARG_PERMISSIONS, permissions);
            args.putInt(ARG_REQUEST_CODE, requestCode);
            args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
            fragment.setArguments(args);
            return fragment;
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Bundle args = getArguments();
            return new AlertDialog.Builder(getActivity())
                    .setMessage(args.getInt(ARG_MESSAGE))
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String[] permissions = args.getStringArray(ARG_PERMISSIONS);
                                    if (permissions == null) {
                                        throw new IllegalArgumentException();
                                    }
                                    ActivityCompat.requestPermissions(getActivity(),
                                            permissions, args.getInt(ARG_REQUEST_CODE));
                                }
                            })
                    .setNegativeButton(android.R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getActivity(), args.getInt(ARG_NOT_GRANTED_MESSAGE), Toast.LENGTH_SHORT).show();
                                }
                            })
                    .create();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA_PERMISSION:
                if (permissions.length != 1 || grantResults.length != 1) {
                    throw new RuntimeException("Error on requesting camera permission.");
                }
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtils.makeText(this, getResources().getString(R.string.camera_permission_not_granted), 1, ToastUtils.LENGTH_SHORT).show();
                } else {

                    try {
                        mCameraView.start();
                        mCameraView.setFacing(CameraView.FACING_BACK);
                        final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
                        AspectRatio chosenRation = null;
                        for (AspectRatio ratio : ratios) {
                            if ((double) ratio.getX() / (double) ratio.getY() == 16.0 / 9) {
                                chosenRation = ratio;
                            }
                        }

                        if (chosenRation == null) {
                            for (AspectRatio ratio : ratios) {
                                if ((double) ratio.getX() / (double) ratio.getY() == 4.0 / 3) {
                                    chosenRation = ratio;
                                }
                            }
                        }
                        if (chosenRation != null) {
                            mCameraView.setAspectRatio(chosenRation);
                        } else {
                            return;
                        }

                    } catch (RuntimeException e) {
                        ToastUtils.makeText(RecogCarPlateActivity.this, "相机启动异常，请尝试重启手机", ToastUtils.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        AppManager.getAppManager().finishActivity();
    }


    private CameraView.Callback mCallback = new CameraView.Callback() {

        @Override
        public void onCameraOpened(CameraView cameraView) {
        }

        @Override
        public void onCameraClosed(CameraView cameraView) {
            Log.d(TAG, "onCameraClosed");
        }

        @Override
        public void onPictureTaken(CameraView cameraView, final byte[] data) {
            if (data == null) {
                MobclickAgent.onEvent(mContext, "tapScanTagFailed");
                mCameraView.start();
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                return;
            }
            //最初的拍照结果在Camera1 takePictureInternal()
            CameraThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    final int rotation = ImageLoader.getOrientation(data);
                    File file = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "picture.jpg");
                    crop(file, data, rotation);
                    Luban.with(mContext)
                            .load(file)  //传入要压缩的图片
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(File fileparams) {
                                    Logger.d("pixelCompressFile", fileparams.getAbsolutePath());
                                    File newFile = new File(fileparams.getParent() + File.separator + "picCropComp.jpg");
                                    fileparams.renameTo(newFile);
                                    int times = SPUtils.getInstance(mContext).getIntValue(SPKey.MAX_OCR_COUNT);
                                    if (times <= 0) {
                                        times = 1;
                                    }
                                    if (SPUtils.getInstance(mContext).getIntValue(SPKey.OCR_TIMES_CONTT) < times) {
                                        //缓存count
                                        SPUtils.getInstance(mContext).putIntValue(SPKey.OCR_TIMES_CONTT, SPUtils.getInstance(mContext).getIntValue(SPKey.OCR_TIMES_CONTT) + 1);
                                        // 调用车牌识别服务
                                        InputStream in = null;
                                        try {
                                            in = new FileInputStream(newFile);
                                            byte[] bytes = new byte[in.available()];
                                            in.read(bytes);
                                            getOcrResult(Base64.encodeToString(bytes, Base64.DEFAULT));
                                            in.close();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            Logger.i("CAMERA_DECODE", "失败" + e.getMessage());
                                            mCameraView.start();
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    dismissLoadingDialog();
                                                    ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                                                }
                                            });
                                        }
                                    } else {
                                        mCameraView.start();
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                dismissLoadingDialog();
                                                ToastUtils.makeText(mContext, "今日扫描次数过多。", ToastUtils.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                }


                                @Override
                                public void onError(Throwable e) {
                                    MobclickAgent.onEvent(mContext, "tapScanTagFailed");
                                    mCameraView.start();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            dismissLoadingDialog();
                                            ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }).launch();    //启动压缩
                }
            });
        }
    };

    private void getOcrResult(String base64Image) {
        // 调用车牌识别
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("image", base64Image);
            bodyJson.put("multi_detect", false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).OCRLicensePlate(body).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OcrResultBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(OcrResultBean resultBean) {
                        // 调用成功，返回OcrResponseResult对象

                        if (resultBean.getMsg_code() == 200
                                && resultBean.getAttachment() != null
                                && resultBean.getAttachment().getWords_result() != null
                                && !TextUtils.isEmpty(resultBean.getAttachment().getWords_result().getNumber())) {
                            number = resultBean.getAttachment().getWords_result().getNumber();
                            getCarMessageByLicense(number);
                        } else {
                            mCameraView.start();
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mCameraView.start();
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 拍摄后的照片。需要进行裁剪。有些手机（比如三星）不会对照片数据进行旋转，而是将旋转角度写入EXIF信息当中，
     * 所以需要做旋转处理。
     *
     * @param outputFile 写入照片的文件。
     * @param data       原始照片数据。
     * @param rotation   照片exif中的旋转角度。
     * @return 裁剪好的bitmap。
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    private void crop(File outputFile, byte[] data, int rotation) {
        try {
            //BitmapRegionDecoder不会将整个图片加载到内存。
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(data, 0, data.length, true);

            //屏幕宽高
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            int screenHeight = getResources().getDisplayMetrics().heightPixels;

            //取景框的宽高，在屏幕的位置
            Rect box = mQrCodeFinderView.getRect();
            int widthBottom = box.width();
            int heightBottom = box.height();
            int leftBox = box.left;
            int topBox = box.top;
            int rightBox = box.right;
            int bottomBox = box.bottom;
            //照片的宽高，旋转成0度后的
            int rawPicWidth = rotation % 180 == 0 ? decoder.getWidth() : decoder.getHeight();
            int rawPicHeight = rotation % 180 == 0 ? decoder.getHeight() : decoder.getWidth();

            //要裁切图片的区域
            Rect region = new Rect();
            int leftRegion = (int) (leftBox * rawPicWidth / (double) screenWidth);
            int topRegion = (int) (topBox * rawPicHeight / (double) screenHeight);
            int rightRegion = (int) (rightBox * rawPicWidth / (double) screenWidth);
            int bottomRegion = (int) (bottomBox * rawPicHeight / (double) screenHeight);

            //如果取景框高度大于图片高度，图片高度不裁剪
            if (heightBottom >= rawPicHeight) {
                topRegion = 0;
                bottomRegion = rawPicHeight;
                //如果取景框宽度大于图片宽度，图片宽度不裁剪
            } else if (widthBottom >= rawPicWidth) {
                leftRegion = 0;
                rightRegion = rawPicWidth;
            }
            region.left = leftRegion;
            region.top = topRegion;
            region.right = rightRegion;
            region.bottom = bottomRegion;

            // 原图为90度旋转
            if (rotation == 90) {
                // 计算，裁剪框旋转后的坐标
                region.left = topRegion;
                region.top = rightRegion;
                region.right = bottomRegion;
                region.bottom = leftRegion;
                region.sort();
            } else if (rotation == 180) {
                // 计算，裁剪框旋转后的坐标
                region.left = leftRegion;
                region.top = rawPicHeight - bottomRegion;
                region.right = rightRegion;
                region.bottom = rawPicHeight - topRegion;
                region.sort();
            } else if (rotation == 270) {
                // 计算，裁剪框旋转后的坐标
                region.left = rawPicHeight - bottomRegion;
                region.top = leftRegion;
                region.right = topRegion;
                region.bottom = rightRegion;
                region.sort();
            }

            BitmapFactory.Options options = new BitmapFactory.Options();

            // 最大图片大小。
            int maxPreviewImageSize = 2560;
            int size = Math.min(decoder.getWidth(), decoder.getHeight());
            size = Math.min(size, maxPreviewImageSize);

            options.inSampleSize = ImageLoader.calculateInSampleSize(options, size, size);
            options.inScaled = true;
            options.inDensity = Math.max(options.outWidth, options.outHeight);
            options.inTargetDensity = size;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = decoder.decodeRegion(region, options);

            if (rotation != 0) {
                // 只能是裁剪完之后再旋转了。有没有别的更好的方案呢？
                Matrix matrix = new Matrix();
                matrix.postRotate(rotation);
                Bitmap rotatedBitmap = Bitmap.createBitmap(
                        bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
                if (bitmap != rotatedBitmap) {
                    // 有时候 createBitmap会复用对象
                    bitmap.recycle();
                }
                bitmap = rotatedBitmap;
            }

            try {
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getCarMessageByLicense(String License) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoadingDialog();
            }
        });
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getCarMessageByLicense(((MyApplication) getApplication()).getRequestFieldMap(), License).enqueue(new Callback<CarDetailBean>() {
            @Override
            public void onResponse(Call<CarDetailBean> call, Response<CarDetailBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, "识别成功！", ToastUtils.LENGTH_SHORT).show();
                        Logger.i("CAMERA_DECODE", "车牌识别成功");
                        Intent intent = new Intent(RecogCarPlateActivity.this, ScanResultActivity.class);
                        intent.putExtra("CarModel", response.body().getAttachment().getCarModel());
                        startActivity(intent);
                        AppManager.getAppManager().finishActivity();
                    } else if (response.body().getStatus() == 20) {
                        ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().finishAllActivity();
                    } else {

                        mCameraView.start();
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {

                    mCameraView.start();
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CarDetailBean> call, Throwable t) {

                mCameraView.start();
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

}
